#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

import json
from typing import List

from alibabacloud_bssopenapi20171214.client import Client as BssOpenApi20171214Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_bssopenapi20171214 import models as bss_open_api_20171214_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_console.client import Client as ConsoleClient
from alibabacloud_tea_util.client import Client as UtilClient

from wingman import logger
from wingman.common.error import ErrorCode
from config.rules_help import ALIYUN_HELP
from config.system import ALIYUN_ACCESS_KEY_ID, ALIYUN_ACCESS_KEY_SECRET


class Business:

    def __init__(self, task: str = None, data: str = None):
        """
        使用AK&SK初始化账号Client
        @return: Client
        @throws Exception
        建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html
        Endpoint 请参考 https://api.aliyun.com/product/BssOpenApi
        """
        self.config = open_api_models.Config(access_key_id=ALIYUN_ACCESS_KEY_ID, access_key_secret=ALIYUN_ACCESS_KEY_SECRET)
        self.config.endpoint = f'business.aliyuncs.com'
        self.client = BssOpenApi20171214Client(self.config)
        # 定义可用的方法映射
        self.methods = {
            'billing': self.billing_cycle,
            # 在这里添加其他方法...
        }
        # # 如果提供了 task 和 data，直接执行并返回结果
        # if task and isinstance(task, str) and task in self.methods:
        #     return self.methods[task]([data] if data else [])

    def __call__(self, task: str = None, data: str = None) -> str:
        """
        允许实例像函数一样被调用
        @param task: 方法名称（字符串）
        @param data: 方法参数
        """
        try:
            result = self.methods[task]([data] if data else [])   # 确保 data 作为列表传递给方法
            return {"result_msg": result}
        except Exception as error:
            result = {"result_msg": "".join(f"请确保输入正确{error}\n- @bot [空格] aliyun [空格] {key} [空格] {value} \n" for key, value in ALIYUN_HELP.items())}
            logger.error(ErrorCode.ALIYUN_CALL.value, result, __name__)
            return result

    # # @staticmethod
    # def __create_client(self) -> BssOpenApi20171214Client:
    #     return BssOpenApi20171214Client(self.config)

    def billing_cycle(self, args: List[str]) -> str:
        """阿里云月使用价格查询 QueryBillOverview """

        if len(args) > 0:
            billing_cycle = args[0]
        else:
            raise ValueError("Billing cycle must be provided.")

        # client = self.__create_client()
        query_bill_overview_request = bss_open_api_20171214_models.QueryBillOverviewRequest(billing_cycle=billing_cycle)
        runtime = util_models.RuntimeOptions()

        try:
            resp = self.client.query_bill_overview_with_options(query_bill_overview_request, runtime)
        except Exception as error:
            logger.error(57000, error.data.get("Recommend"), UtilClient.assert_as_string(error.message))
            return ConsoleClient.log(UtilClient.to_jsonstring(resp))    # 阿里包SDK输出日志

        data = json.loads(UtilClient.to_jsonstring(resp))
        items = data['body']['Data']['Items']['Item']

        total_pretax_amount = 0  # 初始化一个累加器变量
        message = f'查询月份: {args} \n'
        for item in items:
            product_detail = item.get('ProductDetail')
            pretax_amount = item.get('PretaxAmount')
            message += f'产品: {product_detail}, 费用: {pretax_amount}元 \n'
            total_pretax_amount += pretax_amount         # 将 PretaxAmount 累加
        message += f'总费用: {total_pretax_amount:.2f}元'
        logger.info(ErrorCode.SUCCESS.value, message, __name__)
        return message











if __name__ == '__main__':
    billing_cycle = "2025-03"
    billing = Business()
    print(billing("billing_", "2025-03"))

    """
    {
                "headers": {
                    "date": "Thu, 06 Mar 2025 09:52:10 GMT",
                    "content-type": "application/json;charset=utf-8",
                    "content-length": "3198",
                    "connection": "keep-alive",
                    "keep-alive": "timeout=25",
                    "vary": "Accept-Encoding",
                    "access-control-allow-origin": "*",
                    "access-control-expose-headers": "*",
                    "x-acs-request-id": "7D866783-2D6C-568C-A6A8-543V22T52562",
                    "x-acs-trace-id": "e033aa274fae48f3046173c460000000",
                    "etag": "3JQrVZyJpzQfdBnN02000000"
                },
                "statusCode": 200,
                "body": {
                    "Code": "Success",
                    "Data": {
                        "AccountID": "0000000000000000",
                        "AccountName": "账号名",
                        "BillingCycle": "2025-03",
                        "Items": {
                            "Item": [
                                {
                                    "AdjustAmount": 0,
                                    "BillAccountID": "0000000000000000",
                                    "BillAccountName": "账号名",
                                    "BizType": "",
                                    "CashAmount": 0,
                                    "CommodityCode": "snapshot",
                                    "Currency": "CNY",
                                    "DeductedByCashCoupons": 0,
                                    "DeductedByCoupons": 0,
                                    "DeductedByPrepaidCard": 0,
                                    "InvoiceDiscount": 0,
                                    "Item": "PayAsYouGoBill",
                                    "OutstandingAmount": 21.53,
                                    "OwnerID": "0000000000000000",
                                    "PaymentAmount": 0,
                                    "PipCode": "disk",
                                    "PretaxAmount": 21.53,
                                    "PretaxGrossAmount": 21.5332490088,
                                    "ProductCode": "snapshot",
                                    "ProductDetail": "云服务器ECS-快照",
                                    "ProductName": "块存储",
                                    "ProductType": "snapshot",
                                    "RoundDownDiscount": 0.0032490088,
                                    "SubscriptionType": "PayAsYouGo"
                                },
                                {
                                    "AdjustAmount": 0,
                                    "BillAccountID": "0000000000000000",
                                    "BillAccountName": "账号名",
                                    "BizType": "",
                                    "CashAmount": 0,
                                    "CommodityCode": "eip",
                                    "Currency": "CNY",
                                    "DeductedByCashCoupons": 0,
                                    "DeductedByCoupons": 0,
                                    "DeductedByPrepaidCard": 0,
                                    "InvoiceDiscount": 0,
                                    "Item": "PayAsYouGoBill",
                                    "OutstandingAmount": 17.11,
                                    "OwnerID": "0000000000000000",
                                    "PaymentAmount": 0,
                                    "PipCode": "eip",
                                    "PretaxAmount": 17.11,
                                    "PretaxGrossAmount": 17.1184,
                                    "ProductCode": "eip",
                                    "ProductDetail": "弹性公网IP",
                                    "ProductName": "弹性公网IP",
                                    "ProductType": "",
                                    "RoundDownDiscount": 0.0084,
                                    "SubscriptionType": "PayAsYouGo"
                                },
                                {
                                    "AdjustAmount": 0,
                                    "BillAccountID": "0000000000000000",
                                    "BillAccountName": "账号名",
                                    "BizType": "",
                                    "CashAmount": 0,
                                    "CommodityCode": "nat_gw",
                                    "Currency": "CNY",
                                    "DeductedByCashCoupons": 0,
                                    "DeductedByCoupons": 0,
                                    "DeductedByPrepaidCard": 0,
                                    "InvoiceDiscount": 9.707675895,
                                    "Item": "PayAsYouGoBill",
                                    "OutstandingAmount": 55.01,
                                    "OwnerID": "0000000000000000",
                                    "PaymentAmount": 0,
                                    "PipCode": "nat",
                                    "PretaxAmount": 55.01,
                                    "PretaxGrossAmount": 64.7178393,
                                    "ProductCode": "nat_gw",
                                    "ProductDetail": "NAT网关（按量付费）",
                                    "ProductName": "NAT网关",
                                    "ProductType": "",
                                    "RoundDownDiscount": 0.000163405,
                                    "SubscriptionType": "PayAsYouGo"
                                },
                                {
                                    "AdjustAmount": 0,
                                    "BillAccountID": "0000000000000000",
                                    "BillAccountName": "账号名",
                                    "BizType": "",
                                    "CashAmount": 0,
                                    "CommodityCode": "vm",
                                    "Currency": "CNY",
                                    "DeductedByCashCoupons": 0,
                                    "DeductedByCoupons": 0,
                                    "DeductedByPrepaidCard": 0,
                                    "InvoiceDiscount": 0,
                                    "Item": "PayAsYouGoBill",
                                    "OutstandingAmount": 0,
                                    "OwnerID": "0000000000000000",
                                    "PaymentAmount": 0,
                                    "PipCode": "ecs",
                                    "PretaxAmount": 0,
                                    "PretaxGrossAmount": 0,
                                    "ProductCode": "ecs",
                                    "ProductDetail": "云服务器ECS-包年包月",
                                    "ProductName": "云服务器 ECS",
                                    "ProductType": "",
                                    "RoundDownDiscount": 0,
                                    "SubscriptionType": "PayAsYouGo"
                                },
                                {
                                    "AdjustAmount": 0,
                                    "BillAccountID": "0000000000000000",
                                    "BillAccountName": "账号名",
                                    "BizType": "",
                                    "CashAmount": 0,
                                    "CommodityCode": "cfw_elasticity_public_cn",
                                    "Currency": "CNY",
                                    "DeductedByCashCoupons": 0,
                                    "DeductedByCoupons": 0,
                                    "DeductedByPrepaidCard": 0,
                                    "InvoiceDiscount": 0,
                                    "Item": "PayAsYouGoBill",
                                    "OutstandingAmount": 30.27,
                                    "OwnerID": "0000000000000000",
                                    "PaymentAmount": 0,
                                    "PipCode": "cfw",
                                    "PretaxAmount": 30.27,
                                    "PretaxGrossAmount": 30.2791272,
                                    "ProductCode": "cfw",
                                    "ProductDetail": "云防火墙（按量付费）",
                                    "ProductName": "云防火墙",
                                    "ProductType": "cfw_elasticity_public_cn",
                                    "RoundDownDiscount": 0.0091272,
                                    "SubscriptionType": "PayAsYouGo"
                                }
                            ]
                        }
                    },
                    "Message": "Successful!",
                    "RequestId": "7D866783-2D6C-568C-A6A8-543V22T52562",
                    "Success": true
                }
            }
    """
